import 'package:flutter/cupertino.dart';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:home_framework/api/dynamic_service.dart';
import 'package:home_framework/models/dynamic_entity.dart';

class DynamicDetailModel with ChangeNotifier {
  DynamicEntity? _currentDynamic;
  DynamicEntity? get currentDynamic => _currentDynamic;
  bool _praised = false;
  int _praiseCount = 0;
  int get praiseCount => _praiseCount;

  bool _favored = false;
  int _favorCount = 0;
  int get favorCount => _favorCount;

  Future<bool> getDynamic(String id) async {
    EasyLoading.showInfo('加载中...', maskType: EasyLoadingMaskType.black);
    if (_currentDynamic?.id != id) {
      _currentDynamic = null;
    }
    var response = await DynamicService.get(id);
    if (response != null && response.statusCode == 200) {
      _currentDynamic = DynamicEntity.fromJson(response.data);
      notifyListeners();

      EasyLoading.dismiss();
      return true;
    } else {
      EasyLoading.showInfo(response?.statusMessage ?? '请求失败');
      return false;
    }
  }

  Future<bool> updateViewCount() async {
    var response = await DynamicService.updateViewCount(_currentDynamic!.id);
    if (response != null && response.statusCode == 200) {
      _currentDynamic?.viewCount = response.data['viewCount'];
      // 如果元素在列表中，则更新
      notifyListeners();
      return true;
    }
    return false;
  }

  void updatePraiseCount() {
    if (_praised) {
      _praiseCount--;
      _praised = false;
    } else {
      _praiseCount++;
      _praised = true;
    }
    notifyListeners();
  }

  void updateFavorCount() {
    if (_favored) {
      _favorCount--;
      _favored = false;
    } else {
      _favorCount++;
      _favored = true;
    }
    notifyListeners();
  }
}
